<?php
/**
 * Created by : PhpStorm
 * User: 1971229701@qq.com
 * Date: 2020/8/25/025
 * Time: 9:31
 */

namespace app\common\helper;

/**
 * 日期时间处理
 * Class TimeHandle
 * @package app\common\helper
 */
class TimeHandle
{
    /**
     * 每月的第一天和最后一天
     * @param $timestamp
     * @return array
     */
    public static function time($timestamp)
    {
        $y = date('y', $timestamp);
        $m = date('m', $timestamp);
        $start_time = date('Y-m-d H:i:s', strtotime(date($y . '-' . $m, time()) . '-01 00:00:00'));
        $end_time = date('Y-m-d H:i:s', mktime(23, 59, 59, date($m), 31, date($y)));
        return compact('start_time', 'end_time');
    }

    /**
     * 时间日期搜索
     * @param string $start_time 开始时间
     * @param string $end_time 结束时间
     * @param string $field 字段名称
     * @param string $prefix 前缀
     * @return array
     */
    public static function timeSearch($start_time = '', $end_time = '', $field = '', $prefix = '')
    {

        if (!empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00', $start_time);
        }
        if (!empty($end_time)) {
            $end_time = date('Y-m-d 23:59:59', $end_time);
        }
        if (!empty($prefix)) {
            $prefix = $prefix . '.';
        }
        if (empty($start_time) && empty($end_time)) {
            $where = [];
        } else {
            if (!empty($start_time) && !empty($end_time)) {
                $where[$prefix . $field] = ['between', [$start_time, $end_time]];
            } elseif (!empty($start_time) && empty($end_time)) {
                $where[$prefix . $field] = ['>', $start_time];
            } elseif (empty($start_time) && !empty($end_time)) {
                $where[$prefix . $field] = ['<', $end_time];
            }
        }

        return $where;
    }

    /**
     * 过去时间距离现在多久
     * @param $time
     * @return string
     */
    public static function timeDifference($time)
    {
        $time = strtotime($time);
        $rtime = date("m-d H:i", $time);
        $htime = date("H:i", $time);
        $time = time() - $time;
        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor($time / 60);
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor($time / (60 * 60));
            $str = $h . '小时前 ' . $htime;
        } else {
            $d = floor($time / (60 * 60 * 24));
            $str = $d . "天前";
        }
        return $str;
    }
}